import mysql.connector
from mysql.connector import Error

try:
    # 连接到 MySQL 服务器
    connection = mysql.connector.connect(
        host='localhost',
        user='root',
        password='123456'
    )
    if connection.is_connected():
        cursor = connection.cursor()
        # 创建 user_db 数据库（如果不存在）
        cursor.execute("CREATE DATABASE IF NOT EXISTS user_db")
        # 连接到 user_db 数据库
        connection.database = 'user_db'

        # 检查 user 表是否存在
        cursor.execute("SHOW TABLES LIKE 'user'")
        result = cursor.fetchone()
        if result:
            print("user 表已存在！")
        else:
            # 创建 user 表
            create_table_query = """
            CREATE TABLE IF NOT EXISTS user (
                id int AUTO_INCREMENT PRIMARY KEY,
                username VARCHAR(255)NOT NULL,
                realname VARCHAR(255)NOT NULL,
                password VARCHAR(255)NOT NULL,
                idcard VARCHAR(255) NOT NULL,
                phone VARCHAR(255)NOT NULL
            )
            """
            cursor.execute(create_table_query)
            print("user 表创建成功！")

        # 检查 admin 表是否存在
        cursor.execute("SHOW TABLES LIKE 'admin'")
        result = cursor.fetchone()
        if result:
            print("admin 表已存在！")
        else:
            # 创建 admin 表
            create_admin_table_query = """
            CREATE TABLE IF NOT EXISTS admin (
                id int AUTO_INCREMENT PRIMARY KEY,
                username VARCHAR(255)NOT NULL,
                password VARCHAR(255) NOT NULL
            )
            """
            cursor.execute(create_admin_table_query)
            print("admin 表创建成功！")

        # 插入数据到 admin 表
        insert_admin_query = "INSERT INTO admin (username, password) VALUES (%s, %s)"
        admin_data = ('admin', '123456')  # 管理员密码单独设置
        cursor.execute(insert_admin_query, admin_data)
        connection.commit()
        print("数据插入 admin 表成功！")

except Error as e:
    print(f"Error: {e}")
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL 连接已关闭。")